package com.yifeng.repo.tookit.oss.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.yifeng.repo.tookit.oss.model.OssObject;
import com.yifeng.repo.tookit.oss.model.Signature;
import feign.Feign;
import lombok.Data;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Data
public class FileService {
    private final String fireOssUrl;
    private final String merchantId;
    private final String accessToken;
    private Map<String, FileFeign> fileFeignCache = new ConcurrentHashMap<>(4);

    public Signature apply(String appId, String path) {
        return Strings.isNullOrEmpty(merchantId) ? getFileFeign().apply(appId, path) :
                getFileFeign().apply(merchantId, appId, path);
    }

    /**
     * 申请特别许可，支持根据type写入到特定目录下
     * 【注意】暂时不支持删除操作
     */
    public Signature applySpecialPermit(String type, String path) {
        return getFileFeign().applySpecialPermit(type, path);
    }

    public List<OssObject> list(String merchantId, String appId, String path) {
        return getFileFeign().list(merchantId, appId, path);
    }

    public void delete(String merchantId, String appId, String path) {
        getFileFeign().delete(merchantId, appId, path);
    }

    private FileFeign getFileFeign() {
        if (fileFeignCache.containsKey(fireOssUrl)) {
            return fileFeignCache.get(fireOssUrl);
        }
        HttpMessageConverter<Object> jacksonConverter = new MappingJackson2HttpMessageConverter(new ObjectMapper());
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
        // do not use default encoder and decoder
        FileFeign fileService = Feign.builder()
                .encoder(new SpringEncoder(objectFactory))
                .decoder(new SpringDecoder(objectFactory))
                .target(FileFeign.class, fireOssUrl);
        fileFeignCache.put(fireOssUrl, fileService);
        return fileService;
    }
}
